﻿namespace WMS6.SQLServerDAL
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Data.SqlClient;
    using System.Text;
    using WMS6.Common;
    using WMS6.DataEntity;
    using WMS6.DBUtility;
    using WMS6.IDAL;
    using WMS6.QueryEntity;

    public class UserWhDA : IUserWhDA
    {
        private string CREATED_BY = "@CREATED_BY";
        private string IS_DEFAULT = "@IS_DEFAULT";
        private string SQL_CHECK_USER_WH_ID_UNIQUE = " SELECT COUNT(1) FROM @_@USER_WH WHERE WH_DB_ID = @WH_DB_ID AND USER_ID = @USER_ID ";
        private string SQL_DELETE_USER_WH = " DELETE FROM @_@USER_WH WHERE WH_DB_ID = @WH_DB_ID AND USER_ID = @USER_ID ";
        private string SQL_INSERT_USER_WH = " INSERT INTO @_@USER_WH ( USER_ID, WH_DB_ID, IS_DEFAULT, CREATED_BY, CREATED_DATE, UPDATED_BY, UPDATED_DATE) VALUES ( @USER_ID, @WH_DB_ID, @IS_DEFAULT, @CREATED_BY, GETDATE(), @UPDATED_BY, GETDATE() )  ";
        private string SQL_SELECT_ALL_USER_WH = " SELECT  ROWID, USER_ID, WH_DB_ID, IS_DEFAULT, TS, CREATED_BY, CREATED_DATE, UPDATED_BY, UPDATED_DATE  FROM  @_@USER_WH ";
        private string SQL_UPDATE_USER_WH = " UPDATE @_@USER_WH SET IS_DEFAULT = @IS_DEFAULT, UPDATED_BY = @UPDATED_BY, UPDATED_DATE = GETDATE() WHERE WH_DB_ID = @WH_DB_ID AND USER_ID = @USER_ID  ";
        private string TS = "@TS";
        private string UPDATED_BY = "@UPDATED_BY";
        private string USER_ID = "@USER_ID";
        private string WH_DB_ID = "@WH_DB_ID";

        public bool CheckUserWhIDUnique(string userID, string wh_db_ID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@WH_DB_ID", wh_db_ID), new SqlParameter("@USER_ID", userID) };
            return (DBHelper.ExecuteScalar(CommandType.Text, this.SQL_CHECK_USER_WH_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public bool CheckUserWhIDUnique(DataBase dataBase, DbTransaction tran, string userID, string wh_db_ID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@WH_DB_ID", wh_db_ID), new SqlParameter("@USER_ID", userID) };
            return (dataBase.ExecuteScalar(tran, CommandType.Text, this.SQL_CHECK_USER_WH_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public int DeleteUserWh(string userID, List<string> whLoginID)
        {
            int result = 0;
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    string StrSql = "DELETE FROM @_@USER_WH WHERE  USER_ID = '" + userID + "'";
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, StrSql.Replace("@_@", whLoginID[i]));
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int DeleteUserWh(DataBase dataBase, DbTransaction tran, string userID, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    string StrSql = "DELETE FROM @_@USER_WH WHERE  USER_ID = '" + userID + "'";
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, StrSql.Replace("@_@", whLoginID[i]));
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int DeleteUserWh(DataBase dataBase, DbTransaction tran, string wh_db_ID, string userID, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@WH_DB_ID", wh_db_ID), new SqlParameter("@USER_ID", userID) };
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_USER_WH.Replace("@_@", whLoginID[i]), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public DataSet GetAllUserWh(string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_WH.Replace("@_@", whLoginID);
            return DBHelper.ExecuteDataSet(CommandType.Text, sql);
        }

        public DataSet GetAllUserWh(DataBase dataBase, DbTransaction tran, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_WH.Replace("@_@", whLoginID);
            return dataBase.ExecuteDataSet(tran, CommandType.Text, sql);
        }

        public List<DbConfigInfo> GetAuthorizedWHByUserID(string userID)
        {
            List<DbConfigInfo> dbConfigList = new List<DbConfigInfo>();
            StringBuilder StrSql = new StringBuilder();
            StrSql.AppendFormat(" SELECT SD.*,SU.IS_DEFAULT FROM  SYSADM.DB_CONFIG SD INNER JOIN SYSADM.USER_WH SU ON SD.WH_DB_ID = SU.WH_DB_ID  WHERE USER_ID ='{0}'", userID);
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, StrSql.ToString()))
            {
                DbConfigInfo dbConfig = null;
                while (reader.Read())
                {
                    dbConfig = new DbConfigInfo(Convert.ToInt32(reader["wh_db_id"].ToString()), reader["wh_db_name"].ToString(), reader["wh_db_desc"].ToString(), reader["db_dbms"].ToString(), reader["db_database"].ToString(), reader["db_login_id"].ToString(), reader["db_login_passwd"].ToString(), reader["is_global"].ToString(), reader["is_active"].ToString(), reader["is_default"].ToString());
                    dbConfigList.Add(dbConfig);
                }
            }
            return dbConfigList;
        }

        public List<DbConfigInfo> GetUnauthorizedWHByUserID(string userID)
        {
            List<DbConfigInfo> dbConfigList = new List<DbConfigInfo>();
            StringBuilder StrSql = new StringBuilder();
            StrSql.AppendFormat(" SELECT SD.*, ''IS_DEFAULT FROM  SYSADM.DB_CONFIG SD WHERE SD.WH_DB_ID NOT IN (SELECT WH_DB_ID FROM SYSADM.USER_WH WHERE USER_ID ='{0}' )  AND IS_ACTIVE='Y' ", userID);
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, StrSql.ToString()))
            {
                DbConfigInfo dbConfig = null;
                while (reader.Read())
                {
                    dbConfig = new DbConfigInfo(Convert.ToInt32(reader["wh_db_id"].ToString()), reader["wh_db_name"].ToString(), reader["wh_db_desc"].ToString(), reader["db_dbms"].ToString(), reader["db_database"].ToString(), reader["db_login_id"].ToString(), reader["db_login_passwd"].ToString(), reader["is_global"].ToString(), reader["is_active"].ToString(), reader["is_default"].ToString());
                    dbConfigList.Add(dbConfig);
                }
            }
            return dbConfigList;
        }

        public DataSet GetUserWhByQueryList(List<string> sqlWhere, UserWhQueryEntity userwhQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_USER_WH.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            if (!userwhQuery.IsGetAll)
            {
                temp = PagingHelper.GetPagingSQL(temp, userwhQuery.CurrentPage, userwhQuery.PageSize, userwhQuery.SortField, userwhQuery.SortDirection);
            }
            return DBHelper.ExecuteDataSet(CommandType.Text, temp);
        }

        public DataSet GetUserWhByQueryList(DataBase dataBase, DbTransaction tran, List<string> sqlWhere, UserWhQueryEntity userwhQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_USER_WH.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            if (!userwhQuery.IsGetAll)
            {
                temp = PagingHelper.GetPagingSQL(temp, userwhQuery.CurrentPage, userwhQuery.PageSize, userwhQuery.SortField, userwhQuery.SortDirection);
            }
            return dataBase.ExecuteDataSet(tran, CommandType.Text, temp);
        }

        public DbConfigInfo GetUserWhByUserId(string userID)
        {
            StringBuilder StrSql = new StringBuilder();
            StrSql.AppendFormat("  SELECT TOP 1 SD.WH_DB_ID, SD.WH_DB_NAME,SD.IS_GLOBAL,SD.WH_DB_DESC,IS_DEFAULT FROM  SYSADM.DB_CONFIG SD INNER JOIN SYSADM.USER_WH SU ON SD.WH_DB_ID = SU.WH_DB_ID WHERE USER_ID ='{0}' ORDER BY IS_DEFAULT DESC ", userID);
            DbConfigInfo dbConfig = new DbConfigInfo();
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, StrSql.ToString()))
            {
                if (reader.Read())
                {
                    dbConfig.WhDbName = reader["WH_DB_ID"].ToString();
                    dbConfig.IsGlobal = reader["IS_GLOBAL"].ToString();
                    dbConfig.WhDbDesc = reader["WH_DB_DESC"].ToString();
                }
            }
            return dbConfig;
        }

        public int InsertUserWh(UserWhInfo userwhInfo, List<string> whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    SqlParameter[] paras = this.Set_UserWh_Parameters(userwhInfo);
                    if (paras != null)
                    {
                        result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_USER_WH.Replace("@_@", whLoginID[i]), paras);
                    }
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int InsertUserWh(DataBase dataBase, DbTransaction tran, UserWhInfo userWhInfo, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    SqlParameter[] paras = this.Set_UserWh_Parameters(userWhInfo);
                    if (paras != null)
                    {
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_USER_WH.Replace("@_@", whLoginID[i]), paras);
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        private SqlParameter[] Set_UserWh_Parameters(UserWhInfo userWhInfo)
        {
            SqlParameter[] paramArray = new SqlParameter[] { new SqlParameter(this.USER_ID, SqlDbType.VarChar, 20), new SqlParameter(this.WH_DB_ID, SqlDbType.VarChar, 20), new SqlParameter(this.IS_DEFAULT, SqlDbType.VarChar, 1), new SqlParameter(this.CREATED_BY, SqlDbType.VarChar, 20), new SqlParameter(this.UPDATED_BY, SqlDbType.VarChar, 20) };
            paramArray[0].Value = userWhInfo.UserID;
            paramArray[1].Value = userWhInfo.WhDbID;
            if (!string.IsNullOrEmpty(userWhInfo.IsDefault))
            {
                paramArray[2].Value = userWhInfo.IsDefault;
            }
            else
            {
                paramArray[2].Value = DBNull.Value;
            }
            paramArray[3].Value = userWhInfo.CreatedBy;
            paramArray[4].Value = userWhInfo.UpdatedBy;
            return paramArray;
        }

        public int UpdateUserWh(UserWhInfo userWhInfo, List<string> whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    SqlParameter[] paras = this.Set_UserWh_Parameters(userWhInfo);
                    if (paras != null)
                    {
                        result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_USER_WH.Replace("@_@", whLoginID[i]), paras);
                    }
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int UpdateUserWh(DataBase dataBase, DbTransaction tran, UserWhInfo userWhInfo, List<string> whLoginID)
        {
            int result = 0;
            try
            {
                for (int i = 0; i < whLoginID.Count; i++)
                {
                    SqlParameter[] paras = this.Set_UserWh_Parameters(userWhInfo);
                    if (paras != null)
                    {
                        result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_USER_WH.Replace("@_@", whLoginID[i]), paras);
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }
    }
}

